/*
* Copyright (c) 2007 by Windward Studios, Inc. All rights reserved.
*
* This software is the confidential and proprietary information of
* Windward Studios ("Confidential Information").  You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Windward Studios, Inc.
*/

using System;
using System.Text;

namespace Kailua.net.windward.utils
{
	///<summary>
	/// Utility methods that operate on strings.
	///</summary>
	public class StringUtils
	{
		/// <summary>
		/// Returns true if the passe din string is a valid variable name. A valid name uses only [a-z][A-Z][0-9]_ and
		/// does not start with a [0-9].
		/// </summary>
		/// <param name="name">The name of the variable to test.</param>
		/// <returns>true if is a valid var name, false otherwise.</returns>
		static public bool IsValidVarName(string name)
		{

			// must have something
			if (name.Length == 0)
				return false;

			// can't start with [0-9]
			if (Char.IsDigit(name[0]))
				return false;

			// must be [0-9][a-z][A-Z]_
			foreach (char ch in name)
				if ((!Char.IsLetterOrDigit(ch)) && (ch != '_'))
					return false;
			return true;
		}

		/// <summary>
		/// COnvert the name to a valid var name. A valid name uses only [a-z][A-Z][0-9]_ and
		/// does not start with a [0-9].
		/// </summary>
		/// <param name="name">The name to convert.</param>
		/// <returns>The converted name.</returns>
		public static string MakeValidVarName(string name)
		{
			name = name.Replace(' ', '_');
			StringBuilder buf = new StringBuilder();
			foreach (char ch in name)
				if (Char.IsLetterOrDigit(ch) || (ch == '_'))
					buf.Append(ch);
			if (buf.Length == 0)
				buf.Append('_');
			else
				if (Char.IsDigit(buf[0]))
					buf.Insert(0, '_');
			return buf.ToString();
		}
	}
}